<template>
  <div class="cleanup-container">
    <!-- 标题和警告 -->
    <div class="header">
      <el-page-header @back="goBack" title="返回" content="清理文件确认" />
      <el-alert
        title="警告：此操作将永久删除选中的文件，请谨慎操作！"
        type="warning"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 统计信息 -->
    <div class="stats-card">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>删除统计</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">文件总数</div>
              <div class="stat-value">{{ filesToDelete.length }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">总大小</div>
              <div class="stat-value">{{ formatTotalSize }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">所在目录数</div>
              <div class="stat-value">{{ uniqueDirs.length }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <!-- <div style="margin-bottom: 10px; padding: 10px; background: #f0f0f0; border-radius: 4px;">
        <p><strong>调试信息:</strong></p>
        <p>文件列表长度: {{ filesToDelete.length }}</p>
        <p>文件列表内容: {{ JSON.stringify(filesToDelete, null, 2) }}</p>
        <p>路由查询参数: {{ JSON.stringify(route.query, null, 2) }}</p>
      </div> -->
      <!-- 使用v-if确保数据存在时才渲染表格 -->
      <el-card v-show="filesToDelete && filesToDelete.length > 0">
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>文件列表 (共 {{ totalFiles }} 个文件)</span>
            <el-text type="info">每页显示 {{ pageSize }} 条记录</el-text>
          </div>
        </template>
        

        
        <el-table 
          :data="filesToDelete.slice((currentPage - 1) * pageSize, currentPage * pageSize)" 
          :key="tableKey"
          style="width: 100%" 
          border
          stripe
          max-height="500"
        >
          <el-table-column type="index" label="#" width="60" :index="(index) => (currentPage - 1) * pageSize + index + 1" />
          <el-table-column label="文件名" min-width="200">
            <template #default="{ row }">
              {{ row.file_name || '无文件名' }}
            </template>
          </el-table-column>
          <el-table-column label="文件路径" min-width="300">
            <template #default="{ row }">
              {{ row.file_path || '无路径' }}
            </template>
          </el-table-column>
          <el-table-column label="文件大小" width="120">
             <template #default="{ row }">
               <span>{{ formatFileSize(row.file_size || 0) }}</span>
             </template>
           </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div style="margin-top: 20px; display: flex; justify-content: center;">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[20, 50, 100, 200]"
            :total="totalFiles"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange"
            @size-change="handlePageSizeChange"
          />
        </div>
      </el-card>
      
      <!-- 当没有数据时显示提示 -->
      <div v-show="!filesToDelete || filesToDelete.length === 0" style="text-align: center; padding: 40px; color: #999;">
        <el-empty description="暂无要删除的文件" />
      </div>
      

      

       

    </div>

    <!-- 确认区域 -->
    <div class="confirm-area">
      <el-checkbox v-model="confirmChecked">
        我已了解此操作的风险，并确认要删除这些文件
      </el-checkbox>
      <div class="confirm-buttons">
        <el-button @click="goBack">取消</el-button>
        <el-button
          type="danger"
          :disabled="!confirmChecked"
          @click="handleConfirmDelete"
          :loading="deleting"
        >
          确认删除
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useClientStore } from '../stores/client'

// 浏览器兼容的路径处理函数
const getDirname = (filePath: string): string => {
  const lastSlashIndex = filePath.lastIndexOf('/')
  const lastBackslashIndex = filePath.lastIndexOf('\\')
  const lastSeparatorIndex = Math.max(lastSlashIndex, lastBackslashIndex)
  
  if (lastSeparatorIndex === -1) {
    return '.'
  }
  
  return filePath.substring(0, lastSeparatorIndex) || '/'
}



const route = useRoute()
const router = useRouter()
const clientStore = useClientStore()

const filesToDelete = ref<any[]>([])
const confirmChecked = ref(false)
const deleting = ref(false)
const tableKey = ref(0)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(50) // 每页显示50条记录
const totalFiles = ref(0)

// 初始化
onMounted(async () => {
  await loadFiles()
})

// 加载文件列表
const loadFiles = async () => {
  console.log('=== Cleanup.vue loadFiles 开始 ===')
  console.log('完整路由对象:', route)
  console.log('route.query:', route.query)
  console.log('route.params:', route.params)
  console.log('route.query.files:', route.query.files)
  console.log('route.query.files类型:', typeof route.query.files)
  
  if (!route.query.files) {
    console.error('路由中没有files参数！')
    ElMessage.error('没有找到要删除的文件参数')
    goBack()
    return
  }
  
  const fileIds = route.query.files.toString().split(',').map(id => id.trim()).filter(id => id.length > 0)
  console.log('从路由获取的文件ID数组:', fileIds)
  console.log('文件ID数组长度:', fileIds.length)
  
  try {
      // 获取所有状态的文件，不限制状态和分页，获取全部文件
      console.log('开始调用API获取所有文件列表...')
      
      // 首先获取总数
      const totalCount = await clientStore.getScanResultsCount()
      console.log('总文件数量:', totalCount)
      
      // 然后获取所有文件，不限制数量
      const actualLimit = totalCount || 1000
      // console.log(`准备获取文件，limit=${actualLimit}`)
      const response = await clientStore.getScanResults(undefined, 0, actualLimit)
      // console.log('API返回的原始响应:', response)
      // console.log('API返回的文件数量:', response?.length || 0)
      
      if (!response || response.length === 0) {
        console.warn('API返回空的文件列表')
        ElMessage.warning('没有找到可删除的文件')
        goBack()
        return
      }
    
    console.log('要过滤的文件ID列表:', fileIds)
    console.log('API返回的前3个文件示例:', response.slice(0, 3))
    
    // 确保ID类型一致进行比较 (转换为字符串)
    filesToDelete.value = response.filter(
      item => {
        const itemIdStr = String(item.id)
        const match = fileIds.includes(itemIdStr)
        console.log(`检查文件 ID:${item.id}(${itemIdStr}) 文件名:${item.file_name} 是否在选中列表中:`, match)
        console.log(`  - 文件ID类型: ${typeof item.id}`)
        console.log(`  - 转换后ID: ${itemIdStr}`)
        console.log(`  - 是否匹配: ${match}`)
        return match
      }
    ) || []
    
    console.log('过滤后的文件列表:', filesToDelete.value)
    console.log('过滤后的文件数量:', filesToDelete.value.length)
    
    // 设置总文件数量用于分页
    totalFiles.value = filesToDelete.value.length
    
    // 强制更新视图
    await nextTick()
    tableKey.value++
    console.log('视图更新后的文件列表长度:', filesToDelete.value.length)
    
    // 如果没有找到要删除的文件，显示提示
    if (filesToDelete.value.length === 0) {
      console.log('没有找到匹配的文件，显示警告')
      ElMessage.warning('没有找到要删除的文件')
    }
  } catch (error) {
    console.error('=== 加载文件列表失败详细信息 ===')
    console.error('错误对象:', error)
    console.error('错误类型:', typeof error)
    console.error('错误名称:', error?.name)
    console.error('错误消息:', error?.message)
    console.error('错误堆栈:', error?.stack)
    
    if (error?.response) {
      console.error('HTTP响应错误:')
      console.error('- 状态码:', error.response.status)
      console.error('- 状态文本:', error.response.statusText)
      console.error('- 响应数据:', error.response.data)
      console.error('- 响应头:', error.response.headers)
    }
    
    if (error?.request) {
      console.error('HTTP请求错误:')
      console.error('- 请求对象:', error.request)
      console.error('- 请求URL:', error.config?.url)
      console.error('- 请求方法:', error.config?.method)
    }
    
    console.error('=== 错误信息结束 ===')
    
    ElMessage.error(`加载文件列表失败: ${error?.message || '未知错误'}`)
    goBack()
  }
  
  console.log('=== Cleanup.vue loadFiles 结束 ===')
}

// 计算属性
const uniqueDirs = computed(() => {
  const dirs = new Set(
    filesToDelete.value.map(file => getDirname(file.file_path))
  )
  return Array.from(dirs)
})

const formatTotalSize = computed(() => {
  const total = filesToDelete.value.reduce((sum, file) => sum + file.file_size, 0)
  return formatFileSize(total)
})

// 分页数据
const paginatedFiles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filesToDelete.value.slice(start, end)
})

// 分页处理函数
const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 确认删除
const handleConfirmDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除选中的文件，是否继续？',
      '最终确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    deleting.value = true
    let result;
    try {
      // 确保文件ID是整数类型
      const fileIds = filesToDelete.value.map(f => {
        const numId = Number(f.id);
        if (isNaN(numId)) {
          throw new Error(`无效的文件ID: ${f.id}`);
        }
        return numId;
      });
      
      console.log('发送删除请求，文件ID:', fileIds);
      console.log('发送删除请求，文件ID类型:', fileIds.map(id => typeof id));
      console.log('发送删除请求，JSON字符串:', JSON.stringify(fileIds));
      
      result = await clientStore.deleteFiles(fileIds);
    } catch (innerError) {
      console.error('处理文件ID时出错:', innerError);
      throw innerError;
    }

    if (result && result.success) {
      ElMessage.success('文件删除成功')
      router.push('/')
    } else {
      throw new Error('删除失败：' + result.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    deleting.value = false
  }
}
</script>

<style scoped>
.cleanup-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;

  :deep(.el-alert) {
    margin-top: 20px;
  }
}

.stats-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.file-list {
  margin-bottom: 20px;
}

.confirm-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.confirm-buttons {
  display: flex;
  gap: 10px;
}
</style>
